<?php
include_once("sessionmanager.php");
initSession();

if (!isset($_SESSION['s_loggedin']) || ($_SESSION['s_loggedin'] == false) || !isset($_SESSION['s_serverurl']) || (strpos($_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'],$_SESSION['s_serverurl']) === false)) {
	$error_page_code = "timeout";
	include "errorpage.php";
	exit();	
}
if (!$_SESSION['s_cansearch'] || !$_SESSION['s_caninsert']) {
	$error_page_code = "permission";
	include "errorpage.php";
	exit();	
}
include "languages.php";
include_once "functions.inc.php";
require "config.php";
include "attributes.php";
$userid = $_SESSION['s_userid'];

mysql_connect($dbhost,$dbusername,$dbpassword) or die(PARSER_ERROR3);
mysql_select_db($dbname) or die(PARSER_ERROR2);


makeheader(NOTICE_TITLE);

if (isset($_GET['action'])) {
    if ($_GET['action'] == "search" || $_GET['action'] == "searchres") {
        $text = (isset($_POST['searchtext'])) ? $_POST['searchtext'] : "";
        ?>
    		<form name="notice" method="post" action="notices.php?action=searchres">
    		<table cellpadding="1" cellspacing="0" border="0" align="center" width="85%"><tr><td>
    		<table class="standard" cellpadding="4" cellspacing="0" border="0" width="100%">
    		<tr class="tblhead"><td><?php echo NOTICE_SEARCH; ?></td></tr>
    		<tr class="firstcolor"><td style="padding-left:20px;"><?php echo NOTICE_SHOWRESULTS; ?>
            <select name="entries" class="pulldown_code">
            <option value="10" <?php if ($_SESSION['s_hits'] == 10) echo "selected"; ?>>10</option>
            <option value="20" <?php if ($_SESSION['s_hits'] == 20) echo "selected"; ?>>20</option>
            <option value="50" <?php if ($_SESSION['s_hits'] == 50) echo "selected"; ?>>50</option>
            <option value="100" <?php if ($_SESSION['s_hits'] == 100) echo "selected"; ?>>100</option>
            </select>
            </td></tr>
    		<tr class="firstcolor">
    		<td style="padding-left:20px;"><input type="text" class="textfield" name="searchtext" value="<?php echo $text; ?>" style="width:300px;">&nbsp;&nbsp;<input class="button" type="submit" name="<?php echo NOTICE_SEARCH_SHORT; ?>" value="<?php echo NOTICE_SEARCH_SHORT; ?>" /></td>
    		</tr></table>
    		</td></tr>
    		</table>
    		</form>
        <?php
        
    }
    
    if ($_GET['action'] == "searchres") {

        $page = (isset($_GET['page'])) ? $_GET['page'] : 1;
        $entries_per_page = (isset($_GET['entries'])) ? $_GET['entries'] : 20;
        $entries_per_page = (isset($_POST['entries'])) ? $_POST['entries'] : 20;
        $textarray = array();
    
        if (isset($_POST['searchtext']) && !empty($_POST['searchtext'])) {
            if (isset($_SESSION['s_noticesearcharray'])||isset($_SESSION['s_hits'])) {
                unset($_SESSION['s_noticesearcharray']);
                unset($_SESSION['s_hits']);
            }
            $text = stripslashes($_POST['searchtext']);
            $textarray = explode(" ",$text);
            $_SESSION['s_noticesearcharray'] = $textarray;
            $_SESSION['s_hits'] = $entries_per_page;
        } else {
            if (isset($_SESSION['s_noticesearcharray'])) {
                $textarray = $_SESSION['s_noticesearcharray'];
            }
            if (isset($_SESSION['s_hits'])) {
                $entries_per_page = $_SESSION['s_hits'];
            }
        }
        

        if (count($textarray) > 0) {
	        $query = "SELECT count(*) as anzahl
	    			FROM $noticetable n, $utablename ut
	    			WHERE n.userid=ut.id AND n.userid=$userid AND ";
	        foreach ($textarray as $word) {
	            $query .= " noticetext LIKE '%".mysql_real_escape_string($word)."%' AND ";
	        }
	        $query = substr($query,0,strlen($query)-4);
	        $query .= "ORDER BY n.timevalue DESC";
	        $limit = " LIMIT ".(($page-1)*$entries_per_page).",".$entries_per_page;
	        
	        
	        $res = mysql_query($query) or die(mysql_error());
	        $line = mysql_fetch_object($res);
	        $anzahl = $line->anzahl;
	        $query = str_replace("count(*) as anzahl","n.*,ut.username",$query).$limit;
	        $res = mysql_query($query) or die(mysql_error());
	        
	        $i = 0;
	        $found = false;
        } else {
        	$anzahl = 0;
        }
   		?>
   		<table cellpadding="1" cellspacing="0" border="0" align="center" width="95%"><tr><td>
   		<table class="standard" cellpadding="4" cellspacing="0" border="0" width="100%">
   		<?php        

   		if ($anzahl > 0) {
	   		$to = ($page*$entries_per_page < $anzahl) ? $page*$entries_per_page : $anzahl;
	   		echo "<tr><td align=\"center\" class=\"tblhead\" colspan=\"5\">".NOTICE_HITS.": ".(($page-1)*$entries_per_page+1)."-".$to." ".NOTICE_OF." $anzahl<br />";
	   		if ($anzahl > $entries_per_page) {
	   		    draw_pagenumbers($page,$anzahl,$entries_per_page,$_SERVER['PHP_SELF']."?action=searchres","page");
	   		}
	   		echo "</td></tr>";
	   		
	        while ($line = mysql_fetch_object($res)) {
	            // display every entry
	            echo '<tr class="firstcolor"><td>'.NOTICE_DATE.':</td><td>'.date("d.m.Y - H:i",$line->timevalue).'</td></tr>'."\n";
	            echo '<tr class="firstcolor"><td>'.NOTICE_USER.':</td><td>'.$line->username;
	            if ($_SESSION['s_username'] == $line->username) {
	                echo " <a class=\"menulink\" href=\"notices.php?action=edit&amp;coordinates=$line->coordinates\">(".NOTICE_EDIT." /</a>";
	                echo " <a class=\"menulink\" href=\"notices.php?action=delete&amp;coordinates=$line->coordinates\"> ".NOTICE_DELETE.")</a>";
	                $found = true;
	            }
	            echo '</td></tr>'."\n";
	            echo '<tr class="firstcolor"><td>'.NOTICE_TEXT.':</td><td>'.utf8_decode(nl2br($line->noticetext)).'</td></tr>'."\n";
	            if (++$i < mysql_num_rows($res))
	            echo '<tr class="firstcolor"><td colspan="2"><hr></td></tr>'."\n";
	        }
   		} else {
   			echo '<tr class="firstcolor"><td>'.NOTICE_NOTHING.'</td></tr>'."\n";
   		}

        ?>        
            </table>
    		</td></tr>
    		</table>
        <?php
    }
    
    
    if ($_GET['action'] == "deletes") {
        
        if (isset($_POST['coordinates']) && count($_POST['coordinates']) > 0) {
            $where = "";
            foreach ($_POST['coordinates'] as $coords) {
                $where .= "'".mysql_real_escape_string($coords)."',";
            }
            $where = substr($where,0,strlen($where)-1);
            $query = "DELETE FROM $noticetable WHERE userid=$userid AND coordinates IN ($where)";
            $res = mysql_query($query);
            if (!$res) echo "Fehler: ".mysql_error();
            else echo "<div align=\"center\">".NOTICE_DELETED."</div>";
            foreach ($_POST['coordinates'] as $coords) {
                // check if there are any other notices for that coordinates
                $query = "SELECT count(*) as anzahl FROM $noticetable WHERE coordinates='".mysql_real_escape_string($coords)."'";
                $res = mysql_query($query);
                $line = mysql_fetch_object($res);
                $anzahl = $line->anzahl;
                if ($anzahl == 0) {
                    // no notices left
                    $query = "UPDATE $dbtablename SET notices='false' 
                    WHERE userid=$userid AND coordinates='".mysql_real_escape_string($coords)."'";
                    $res = mysql_query($query) or die(mysql_error());
                } else {
                    // at least one entry - no update needed
                } 
            }            
            
        }
        $_GET['action'] = "show";
          
    } 
    if ($_GET['action'] == "show") {
        ?>
<script type="text/javascript">
<!--
var Marker = "false";

function CheckboxenAktivieren(field)
{
	if(Marker=="false")
	{
		for(i=0; i<field.elements.length; i++)
		{
			field[i].checked = true;
		}
		Marker = "true";
		return "<?php echo NOTICE_NONE; ?>";
	}
	else
	{
		for(i=0; i<field.elements.length; i++)
		{
			field[i].checked = false;
		}
		Marker = "false";
		return "<?php echo NOTICE_ALL; ?>";
	}
}
//-->
</script>

    		<form name="notice" method="post" action="notices.php?action=deletes">
    		<table cellpadding="1" cellspacing="0" border="0" align="center" width="95%"><tr><td>
    		<table class="standard" cellpadding="4" cellspacing="2" border="0" width="100%">
    		<tr class="tblhead"><td colspan="3"><?php echo NOTICE_HEADER2; ?></td></tr>
    	<?php
    	
    	//$query = "SELECT * FROM $noticetable WHERE userid=$userid ORDER BY coordinates";
    	$query = "SELECT * FROM $noticetable WHERE userid=$userid ORDER BY timevalue DESC";
    	$res = mysql_query($query);
    	$i = 0;
    	while ($line = mysql_fetch_object($res)) {
    	    $strlen = strlen($line->noticetext);
    	    $strlen = ($strlen > 100) ? 100 : $strlen;
    	    $substring = utf8_decode(nl2br(substr($line->noticetext,0,$strlen)));
        	$coordinates_array = explode(":",$line->coordinates);
    	    if ($strlen == 100) $substring .= "[..]";
    		echo "<tr class=\"firstcolor\"><td width=\"10%\">";
    		echo '<input name="coordinates[]" type="checkbox" value="'.$line->coordinates.'" />';
 		$colorclass = "private";
   		
    		echo "</td><td width=\"10%\"><a class=\"menulink\" href=\"view.php?gala=".$coordinates_array[0]."&amp;system=".$coordinates_array[1]."\">".$line->coordinates."</a><br /><span class=\"$colorclass\">".date("d.m.Y H:i",$line->timevalue)."</span></td><td width=\"80%\"><a href=\"notices.php?action=edit&amp;coordinates=$line->coordinates\" class=\"menulink\">".$substring."</a></td></tr>\n";
    	}
    	
        ?>    		
    		<tr class="firstcolor">
    		<td><input class="button" name="button" type="button" onClick="this.value=CheckboxenAktivieren(document.notice);" value="<?php echo NOTICE_ALL; ?>"></td>
    		<td align="center" colspan="2"><input class="button" type="submit" name="<?php echo NOTICE_DELETE; ?>" value="<?php echo NOTICE_DELETE; ?>" /></td>
    		</tr></table>
    		</td></tr>
    		</table>
    		</form>
      <?php
    }

    if ($_GET['action'] == "save" || $_GET['action'] == "delete" || $_GET['action'] == "edit" || $_GET['action'] == "view") {
    	// get Coordinates
    	$coordinates = (isset($_GET['coordinates'])) ? trim($_GET['coordinates']) : "1:1:1";
    	$coordinates  = preg_replace("/([^0-9:])/","",$coordinates);
    	$coordinates_array = explode(":",$coordinates);
    	
    	if (($_GET['action'] == "save" || $_GET['action'] == "delete") && (count($coordinates_array) == 3)) {
    		
    		// Insert data
    		if ($_GET['action'] == "save") {
        		$text = stripslashes(trim($_POST['text']));
        		$text = str_replace("<","&lt;",$text);
        		$text = str_replace(">","&gt;",$text);
        		$text = utf8_encode($text);
    		}
    
    		if (!isset($text) || empty($text)) {
                $query = "DELETE FROM $noticetable WHERE coordinates='$coordinates' AND userid=$userid";
                $res = mysql_query($query);
                if (!$res) echo "Fehler: ".mysql_error();
                else echo "<div align=\"center\">".NOTICE_DELETED."</div>";
                
                // check if there are any other notices for that coordinates
                $query = "SELECT count(*) as anzahl FROM $noticetable WHERE userid=$userid AND coordinates='$coordinates'";
                $res = mysql_query($query);
                $line = mysql_fetch_object($res);
                $anzahl = $line->anzahl;
                if ($anzahl == 0) {
                    // no notices left
                    $query = "UPDATE $dbtablename SET notices='false' 
                    WHERE userid=$userid AND galaxie='".$coordinates_array[0]."' AND system='".$coordinates_array[1]."' 
                    AND planet='".$coordinates_array[2]."'";
                    $res = mysql_query($query);
                } else {
                    // at least one entry
                    $query = "UPDATE $dbtablename SET notices='true' 
                    WHERE userid=$userid AND galaxie='".$coordinates_array[0]."' AND system='".$coordinates_array[1]."' 
                    AND planet='".$coordinates_array[2]."'";
                    $res = mysql_query($query);
                }
                
    		} else {
        		$query = "REPLACE INTO $noticetable
        		SET noticetext='".mysql_real_escape_string($text)."', 
        			coordinates='$coordinates', userid=$userid, timevalue='".time()."'";
        		$res = mysql_query($query);
        		if (!$res) echo "Fehler: ".mysql_error();
        		else echo "<div align=\"center\">".NOTICE_SAVED."</div>";
                $query = "UPDATE $dbtablename SET notices='true' 
                WHERE userid=$userid AND galaxie='".$coordinates_array[0]."' AND system='".$coordinates_array[1]."' 
                AND planet='".$coordinates_array[2]."'";
                $res = mysql_query($query);    		
    		}
    		$_GET['action'] = "edit";
    	}
    
    	if ($_GET['action'] == "edit" && count($coordinates_array) == 3) {
    		// edit/create data
    
    		// retrieve old notice
    		$text = "";
    		$timevalue = "";
    		$query = "SELECT * FROM $noticetable WHERE coordinates='$coordinates' AND userid=$userid LIMIT 1";
    		$res = mysql_query($query);
    		while ($line = mysql_fetch_object($res)) {
    			$text = utf8_decode($line->noticetext);
    			$timevalue = $line->timevalue;
    		}
    
    		// retrieve data from coordinates
    		$query = "SELECT u.*,p.rank, a.rank as arank, a.members
    			FROM $dbtablename u LEFT JOIN $pstablename p ON (u.userid=p.userid AND u.spielername=p.playername)
    			LEFT JOIN $astablename a ON (u.userid=a.userid AND u.ally=a.allyname)
    			WHERE u.galaxie='".$coordinates_array[0]."' AND u.system='".$coordinates_array[1]."' AND
    			planet='".$coordinates_array[2]."' AND u.userid=$userid LIMIT 1";
    		$res = mysql_query($query);
    		$line = mysql_fetch_object($res);
    
    		?>
            <script language="JavaScript">
            <!--
            var x = "";
            var e = null;
            
            function cntchar(m) {
            	if(window.document.notice.text.value.length > m) {
            		window.document.notice.text.value = x;
            	} else {
            		x = window.document.notice.text.value;
            	}
            	if(e == null)
            	e = document.getElementById('cntChars');
            	else
            	e.childNodes[0].data = window.document.notice.text.value.length;
            }
            //-->
            </script>
    		<form name="notice" method="post" action="notices.php?action=save&amp;coordinates=<?php echo $coordinates; ?>">
    		<table cellpadding="1" cellspacing="0" border="0" align="center" width="95%"><tr><td>
    		<table class="standard" cellpadding="4" cellspacing="0" border="0" width="100%">
    		<tr class="tblhead"><td colspan="2"><a name=""><?php echo NOTICE_HEADER." ($coordinates)"; ?></a></td></tr>
    		<tr class="firstcolor">
    		<td><?php echo NOTICE_TEXT; ?><br>(<span id="cntChars">0</span> / 65000 bytes)</td>
    		<td>
    		<textarea class="textfield" name=text cols=60 rows=20 onkeyup="javascript:cntchar(65000)"><?php echo $text; ?></textarea>
    		</td>
    		</tr>
    		<tr class="firstcolor">
    		<td align="right"><input class="button" type="submit" name="<?php echo NOTICE_SAVE; ?>" value="<?php echo NOTICE_SAVE; ?>" /></td>
    		<td><input class="button" type="reset" name="Reset" value="Reset" /></td>
    		</tr></table>
    		</td></tr>
    		</table>
    		</form>
    
    		<?php
    	}
    
    	if ($_GET['action'] == "view") {
    		// Get all Entries of that planet
    		?>
    		<table cellpadding="1" cellspacing="0" border="0" align="center" width="95%"><tr><td>
    		<table class="standard" cellpadding="4" cellspacing="0" border="0" width="100%">
    		<tr class="tblhead"><td colspan="2"><a name=""><?php echo NOTICE_RESULTS." ($coordinates)"; ?></a></td></tr>
    		<?php
    		$query = "SELECT n.*,ut.username
    			FROM $noticetable n, $utablename ut
    			WHERE n.userid=ut.id AND n.userid=$userid AND n.coordinates='$coordinates'
    			ORDER BY n.timevalue DESC";
    		$res = mysql_query($query);
    		$i = 0;
    		$found = false;
    		while ($line = mysql_fetch_object($res)) {
    			// display every entry
    			echo '<tr class="firstcolor"><td>'.NOTICE_DATE.':</td><td>'.date("d.m.Y - H:i",$line->timevalue).'</td></tr>'."\n";
    			echo '<tr class="firstcolor"><td>'.NOTICE_USER.':</td><td>'.$line->username;
    			if ($_SESSION['s_username'] == $line->username) {
    			    echo " <a class=\"menulink\" href=\"notices.php?action=edit&amp;coordinates=$coordinates\">(".NOTICE_EDIT." /</a>";
    			    echo " <a class=\"menulink\" href=\"notices.php?action=delete&amp;coordinates=$coordinates\"> ".NOTICE_DELETE.")</a>";
    			    $found = true;
    			}
    			echo '</td></tr>'."\n";
			echo '<tr class="firstcolor"><td>'.NOTICE_TEXT.':</td><td>'.utf8_decode(nl2br($line->noticetext)).'</td></tr>'."\n";
        		if (++$i < mysql_num_rows($res))
        			echo '<tr class="firstcolor"><td colspan="2"><hr></td></tr>'."\n";
    		}
    		if (!$found) {
    		    echo '<tr class="firstcolor"><td colspan="2"><hr></td></tr>'."\n";
    		    echo '<tr class="firstcolor"><td colspan="2"><a class="menulink" href="notices.php?action=edit&amp;coordinates='.$coordinates.'">'.NOTICE_NEW.'</a></td></tr>'."\n";
    		}
    		echo '<tr class="firstcolor"><td colspan="2"><a class="menulink" href="notices.php?action=show">'.NOTICE_SHOWALL.'</a></td></tr>'."\n";
    		?>
    		</table>
    		</td></tr>
    		</table>
    		<?php
    	}

    }
} else {
	echo "<div align=\"center\">Keine Aktion festgelegt! / No Action given!!</div>";
}


makefooter();

?>